package classreplace;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.gjt.jclasslib.io.ClassFileWriter;
import org.gjt.jclasslib.structures.ClassFile;
import org.gjt.jclasslib.structures.Constant;
import org.gjt.jclasslib.structures.InvalidByteCodeException;
import org.gjt.jclasslib.structures.constants.ConstantUtf8Info;

public class ClassReplace {
	public static void main(String[] args) throws InvalidByteCodeException, IOException {
		// CAR
		// 替换字符串和查找字符串
		String findex = "10.7.241.7:7894";
		String repleaceEx = "10.7.241.7:6888";
		String DPath = "C:\\Users\\Admin\\Desktop\\classreplace\\web(1)";
		
		// Deal
		// 循环文件夹收集所有class文件路径
		List<String> clzlist = findClazz(DPath);
//		for (String string : clzlist) 
//			System.out.println(string);
		// 根据class文件路径读取并寻找字符串完成替换
		for (String cp : clzlist) {
	        FileInputStream fis = new FileInputStream(cp);
	        DataInput di = new DataInputStream(fis);   
	        ClassFile cf = new ClassFile();   
	        cf.read(di);   
	        Constant[] infos = cf.getConstantPool();
	        boolean needRewrite = false;
	           
	        int count = infos.length;   
	        for (int i = 0; i < count; i++) {   
	            if (infos[i] != null) {   
	                if(infos[i] instanceof ConstantUtf8Info) {
		                ConstantUtf8Info uInfo = (ConstantUtf8Info)infos[i];  
		                String s = uInfo.getString();
		                if(s.contains(findex)){
		                	System.out.println(i+" "+s);
		                    uInfo.setString(s.replaceAll(findex, repleaceEx));  
		                    System.out.println("replaced: "+uInfo.getString());
		                    infos[i]=uInfo;   
		                    needRewrite = true;
		                }
	                }
	            }   
	        }   
	        cf.setConstantPool(infos);   
            fis.close();
            if(needRewrite) {
		        File f = new File(cp);   
	            ClassFileWriter.writeToFile(f, cf);
            }
		}


	}

	private static List<String> findClazz(String fp) {
		List<String> tmp = new ArrayList<>();
		File f = new File(fp);
		File[] lfs = f.listFiles();
		for (File file : lfs) {
			if(file.isDirectory())
				tmp.addAll(findClazz(file.getAbsolutePath()));
			else if(file.getName().endsWith(".class"))
				tmp.add(file.getAbsolutePath());
		}
		return tmp;
	}
}
